package org.jeecg.modules.paycenter.channel.tonglian;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.ImageUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.middleware.rabbitmq.delay.DelayMqUtil;
import org.jeecg.modules.middleware.rabbitmq.delay.tl.TlDelayMessageType;
import org.jeecg.modules.middleware.rabbitmq.gen.EnumGenHandler;
import org.jeecg.modules.middleware.rabbitmq.gen.GenMqUtil;
import org.jeecg.modules.paycenter.enums.UTypeEnum;
import org.jeecg.modules.paycenter.exception.BankSendException;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.tlaccount.entity.HyTlAccount;
import org.jeecg.modules.wlhy.tlaccount.entity.HyTlAccountRecord;
import org.jeecg.modules.wlhy.tlaccount.service.IHyTlAccountRecordService;
import org.jeecg.modules.wlhy.tlaccount.service.IHyTlAccountService;
import org.jeecg.modules.wlhy.utils.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class TongLianMemberService{

    @Autowired
    private IHyTlAccountService tlAccountService;

    @Autowired
    private IHyTlAccountRecordService recordService;

    @Autowired
    private TongLianWalletService walletService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IHyDriverService driverService;

    @Autowired
    private IHyCarrierService carrierService;

    @Autowired
    private IHyDriverBankService driverBankService;

    @Autowired
    private IHyVehicleService vehicleService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;



    public void getPersonMemberInfo(HyTlAccount account) {
        if (!"1".equals(account.getIzOpen())) {
            return;
        }
        String subAcctNo = account.getSubAcctNo();
        if ("1".equals(account.getPaySt()) && StringUtils.isNotEmpty(subAcctNo)) {
            return;
        }
        String izSignContract = account.getIzSignContract();
        String izBindBankCard = account.getIzBindBankCard();
        String izPhoneChecked = account.getIzPhoneChecked();
        String izOcrIdcard = account.getIzOcrIdcard();
        String izOcrRegnum = account.getIzOcrRegnum();

        UTypeEnum uTypeEnum = UTypeEnum.getUTypeEnum(account.getUtype());

        try {
            JSONObject ret = TongLianUtil.getMemberInfo(account.getBizUserId());
            if (TongLianUtil.isSuccess(ret)) {
                JSONObject data = ret.getJSONObject("data");
                if (data == null) {
                    return;
                }
                //account.setMemberInfo(data);
                boolean isNeedUpdate = false;
                String subAcctNo1 = data.getString("subAcctNo");
                if(StringUtils.isEmpty(subAcctNo) && StringUtils.isNotEmpty(subAcctNo1)){
                    isNeedUpdate = true;
                    account.setSubAcctNo(subAcctNo1);
                }

                if (!"1".equals(izPhoneChecked)) {
                    if (data.getBooleanValue("isPhoneChecked")) {
                        isNeedUpdate = true;
                        izPhoneChecked = "1";
                        account.setIzPhoneChecked("1");
                    }
                }

                if (!"1".equals(izBindBankCard)) {
                    JSONArray cardList = data.getJSONArray("cardList");
                    if (cardList != null && cardList.size() > 0) {
                        JSONObject card = cardList.getJSONObject(0);
                        String cardNo = TongLianUtil.decryptAES(card.getString("cardNo"));
                        account.setBankCardNo(cardNo);
                        isNeedUpdate = true;
                        izBindBankCard = "1";
                        account.setIzBindBankCard("1");
                    }
                }

                if (!"1".equals(izSignContract)) {
                    if (data.getBooleanValue("isSignContract")) {
                        isNeedUpdate = true;
                        izSignContract = "1";
                        account.setIzSignContract("1");
                    }
                }

                if (!"1".equals(izOcrIdcard)) {
                    JSONObject memberInfo = data.getJSONObject("memberInfo");
                    String ocrIdcardComparisonResult = null;
                    //String ocrRegnumComparisonResult = null;
                    if (memberInfo != null) {
                        ocrIdcardComparisonResult = memberInfo.getString("ocrIdcardComparisonResult");
                        //ocrRegnumComparisonResult = memberInfo.getString("ocrRegnumComparisonResult");
                    }
                    if ("1".equals(ocrIdcardComparisonResult)) {
                        isNeedUpdate = true;
                        izOcrIdcard = "1";
                        account.setIzOcrIdcard("1");
                    } else if ("0".equals(ocrIdcardComparisonResult)) {
                        isNeedUpdate = true;
                        izOcrIdcard = "0";
                        account.setIzOcrIdcard("0");
                    }
                }

//                if (uTypeEnum == UTypeEnum.DRIVER) {
//                    if (!"1".equals(izOcrRegnum)) {
//                        String isTransportCertificate=data.getString("isTransportCertificate");
//                        if ("1".equals(isTransportCertificate)) {
//                            isNeedUpdate = true;
//                            izOcrRegnum = "1";
//                            account.setIzOcrRegnum("1");
//                        } else if ("0".equals(isTransportCertificate)) {
//                            isNeedUpdate = true;
//                            izOcrRegnum = "0";
//                            account.setIzOcrRegnum("0");
//                        }
//                    }
//                }

                switch (uTypeEnum) {
                    case DRIVER: {
                        //更新账号可交易状态
                        if ("1".equals(izSignContract) &&
                                "1".equals(izBindBankCard) &&
                                "1".equals(izPhoneChecked) &&
                                "1".equals(izOcrIdcard)
//                                &&"1".equals(izOcrRegnum)
                                ) {
                            isNeedUpdate = true;
                            account.setPaySt("1");
                        }
                    }
                    break;
                    case CARRIER: {
                        if ("1".equals(izSignContract) &&
                                "1".equals(izBindBankCard) &&
                                "1".equals(izPhoneChecked) &&
                                "1".equals(izOcrIdcard)) {
                            isNeedUpdate = true;
                            account.setPaySt("1");
                        }
                    }
                    break;
                    default:
                        break;
                }
                if (isNeedUpdate) {
                    tlAccountService.updateById(account);
                    return;
                }
            } else {
                account.setMsg(TongLianUtil.getMsg(ret));
                account.setSt("-99");
            }
        } catch (Exception ex) {
            account.setSt("-99");
            account.setMsg(ex.getMessage());
        }
    }

    @Transactional
    public Result<?> createCustomerAccount(HyCustomer customer, JSONObject data) {
        String uid = customer.getId();
        HyTlAccount account = tlAccountService.getByUid(uid);
        if(account != null){
            return Result.error("已开通钱包,不能重复开通");
        }
        String bizUserId = CodeUtil.createBizUserId(UTypeEnum.CUSTOMER);
        account = new HyTlAccount();
        account.setAccName(customer.getCustomerName());
        account.setUtype(UTypeEnum.CUSTOMER.uType);
        account.setBizUserId(bizUserId);
        account.setPhone(customer.getLoginPhone());
        account.setUid(uid);
        account.setSt("1");
        account.setPaySt("1");
        account.setIzOpen("0");
        account.setAmt(BigDecimal.ZERO);
        account.setAvailAmt(BigDecimal.ZERO);
        account.setFrzAmt(BigDecimal.ZERO);

        account.setIzBindBankCard("0");
        account.setIzPhoneChecked("0");
        account.setIzSignContract("0");
        account.setIzOcrIdcard("0");
        account.setIzOcrRegnum("0");
        tlAccountService.save(account);
        return Result.OK("开通成功!");
    }

    @Transactional
    public Result<?> customerRecharge(HyCustomer customer, JSONObject data) {
        String samt = data.getString("amt");
        String source = data.getString("source");
        if (StringUtils.isEmpty(source)) {
            source = "2";
        }
        if (StringUtils.isEmpty(samt)) {
            return Result.error("金额不能为空！");
        }
        BigDecimal amt = null;
        try {
            amt = new BigDecimal(samt);
        } catch (Exception e) {
            return Result.error("金额格式错误！");
        }
        // 0 > amt
        if (BigDecimal.ZERO.compareTo(amt) == 1) {
            return Result.error("金额错误！");
        }

        String uid = customer.getId();
        HyTlAccount account = tlAccountService.getByUidForUpdate(uid);
        if (account == null) {
            return Result.error("未开通钱包,请先开通钱包");
        }
        String bizUserId = account.getBizUserId();
        String merOrderNo = CodeUtil.getMerOrderNo();
        String payerId = "666666";
        if ("1".equals(account.getIzOpen())) {
            payerId = bizUserId;
        }

        HyTlAccountRecord record = new HyTlAccountRecord();
        record.setOptType(TlOptTypeEnum.RECHARGE._optType);
        record.setRt("1");
        record.setWalletId(account.getId());
        record.setBizUserId(bizUserId);
        record.setUid(uid);
        record.setAmt(amt);
        record.setCostService(BigDecimal.ZERO);
        record.setCostPayShipping(amt);
        record.setSt("0");//待充值
        record.setMerOrderNo(merOrderNo);
        recordService.save(record);

        String sAmount = TongLianUtil.yuanToFen(amt);
        try {
            long expireTime = TongLianUtil._orderExpireDatetime;
            JSONObject ret = TongLianUtil.ystConsumeApply(merOrderNo, payerId,
                    "", "customerRechargeNotify",
                    sAmount, "货主充值", source , expireTime);
            if (!TongLianUtil.isSuccess(ret)) {
                throw new JeecgBootException("充值失败," + TongLianUtil.getMsg(ret));
            }
            JSONObject jd = ret.getJSONObject("data");
            if(jd == null){
                throw new JeecgBootException("充值失败:获取交易数据失败!");
            }
            String payStatus = jd.getString("payStatus");
            if("2".equals(payStatus)){
                String payFailMessage = jd.getString("payFailMessage");
                if(StringUtils.isEmpty(payFailMessage)){
                    payFailMessage = jd.getString("errorMessage");
                }
                throw new JeecgBootException("充值失败:" + payFailMessage);
            }
            record.setPayStatus(jd.getString("payStatus"));
            record.setBizOrderNo(jd.getString("bizOrderNo"));
            record.setOrderNo(jd.getString("orderNo"));
            recordService.updateById(record);
            String payInfo = jd.getString("payInfo");
            //保存到redis中,有效期 60分钟
            String rediskey = "merOrderNo:" + merOrderNo;
            redisUtil.set(rediskey, payInfo, expireTime*60);
            DelayMqUtil.sendTLMsg(TlDelayMessageType.CUSTOMER_RECHARGE_ORDER_EXPIRE, merOrderNo, (int) (expireTime*60 + 10));
            return Result.OK(jd);
        } catch (BankSendException e) {
            throw new JeecgBootException(e.getMessage());
        } catch (Exception e) {
            throw new JeecgBootException(e.getMessage());
        }
    }

    @Transactional
    public void customerRechargeCallback(String merOrderNo, Map<String, String> map){
        HyTlAccountRecord record = recordService.getByMerOrderNoForUpdate(merOrderNo);
        if (record == null) {
            return;
        }
        if ("1".equals(record.getSt())) {
            return;
        }
        if ("2".equals(record.getSt())) {
            return;
        }
        String status = map.get("status");
        if(!"OK".equals(status)){
            record.setSt("2");
            recordService.updateById(record);
            return;
        }
        record.setPayDatetime(map.get("payDatetime"));
        record.setAcct(map.get("acct"));
        record.setPayInterfaceOutTradeNo(map.get("payInterfaceOutTradeNo"));
        record.setSt("1");
        walletService.RechargeCallback(record);
    }

    public String getOrderPayStatus(String merOrderNo) {
        JSONObject ret = TongLianUtil.ystOrderStatusQuery(merOrderNo);
        if (!TongLianUtil.isSuccess(ret)) {
            throw new JeecgBootException(TongLianUtil.getMsg(ret));
        }
        JSONObject jd = ret.getJSONObject("data");
        if (jd == null) {
            throw new JeecgBootException("查询订单交易状态失败，请重试");
        }
        return jd.getString("payStatus");
    }

    public JSONObject getOrderDetail(String merOrderNo) {
        JSONObject ret = TongLianUtil.getOrderDetail(merOrderNo);
        if (!TongLianUtil.isSuccess(ret)) {
            throw new JeecgBootException(TongLianUtil.getMsg(ret));
        }
        JSONObject jd = ret.getJSONObject("data");
        if (jd == null) {
            throw new JeecgBootException("查询订单交易详情失败，请重试");
        }
        return jd;
    }

    @Transactional
    public Result<?> updateOrderNo(HyTlAccountRecord record) {
        String merOrderNo = record.getMerOrderNo();
        String payStatus = getOrderPayStatus(merOrderNo);
        if ("1".equals(payStatus)) {
            record.setSt("1");
            JSONObject orderDetail = getOrderDetail(merOrderNo);
            record.setPayDatetime(orderDetail.getString("payDatetime"));
            record.setAcct(orderDetail.getString("acct"));
            record.setPayInterfaceOutTradeNo(orderDetail.getString("payInterfaceOutTradeNo"));
            walletService.RechargeCallback(record);
            return Result.OK("操作成功");
        } else if ("2".equals(payStatus)) {
            record.setSt("2");
            recordService.updateById(record);
            return Result.OK("操作成功");
        }
        return Result.OK("订单交易进行中,请稍后查询");
    }

    public Result<?> createCompanyAccount(HyCompany company, String source) {
        String uid = company.getId();
        HyTlAccount account = tlAccountService.getByUid(uid);
        if(account != null){
            return Result.error("已开通钱包,不能重复开通");
        }
        String bizUserId = CodeUtil.createBizUserId(UTypeEnum.COMPANY);
        account = new HyTlAccount();
        account.setAccName(company.getCompanyName());
        account.setUtype(UTypeEnum.COMPANY.uType);
        account.setBizUserId(bizUserId);
        account.setPhone(company.getLegalerTel());
        account.setUid(uid);
        account.setSt("1");
        account.setPaySt("1");
        account.setIzOpen("0");
        account.setAmt(BigDecimal.ZERO);
        account.setAvailAmt(BigDecimal.ZERO);
        account.setFrzAmt(BigDecimal.ZERO);

        account.setIzBindBankCard("0");
        account.setIzPhoneChecked("0");
        account.setIzSignContract("0");
        account.setIzOcrIdcard("0");
        account.setIzOcrRegnum("0");
        tlAccountService.save(account);
        return Result.OK("开通成功!");
    }

    @Transactional
    public Result<?> createCarrierAccount(HyCarrier carrier,String source) {
        //检查是否已开通
        String bankName = carrier.getBankName();
        if (StringUtils.isEmpty(bankName)) {
            return Result.error("车队长账户名称不能为空");
        }
        String tel = carrier.getTel();
        if (StringUtils.isEmpty(tel)) {
            return Result.error("车队长手机号不能为空");
        }

        String idcard = carrier.getIdcard();
        if (StringUtils.isEmpty(tel)) {
            return Result.error("车队长身份证号不能为空");
        }

        String idcardimg = carrier.getIdcardImg();
        if (StringUtils.isEmpty(idcardimg)) {
            return Result.error("车队长身份证正面照片不能为空");
        }

        String idcardimgback = carrier.getIdcardImgBack();
        if (StringUtils.isEmpty(idcardimgback)) {
            return Result.error("车队长身份证背面照片不能为空");
        }

        String uid = carrier.getId();
        HyTlAccount account = tlAccountService.getByUid(uid);
        if (account != null) {
            return Result.error("已开通钱包,不能重复开通");
        }

        String bizUserId = CodeUtil.createBizUserId(UTypeEnum.CARRIER);
        account = new HyTlAccount();
        account.setAccName(carrier.getCarrierName());
        account.setUtype(UTypeEnum.CARRIER.uType);
        account.setBizUserId(bizUserId);
        account.setUid(uid);
        account.setPhone(tel);
        account.setSt("1");
        account.setPaySt("0");
        account.setIzOpen("1");
        account.setAmt(BigDecimal.ZERO);
        account.setAvailAmt(BigDecimal.ZERO);
        account.setFrzAmt(BigDecimal.ZERO);
        account.setIzBindBankCard("0");
        account.setIzPhoneChecked("0");
        account.setIzSignContract("0");
        account.setIzOcrIdcard("0");
        account.setIzOcrRegnum("0");
        tlAccountService.save(account);
        JSONObject ret = TongLianUtil.createPersonMember(bizUserId, bankName, idcard, "3", tel, null, source);
        if (!TongLianUtil.isSuccess(ret)) {
            throw new JeecgBootException("开通失败," + TongLianUtil.getMsg(ret));
        }
        JSONObject jd = ret.getJSONObject("data");
        String tlUserId = jd.getString("userId");//云商通会员号
        account.setTlUserId(tlUserId);
        tlAccountService.updateById(account);
        //异步上传 照片
        GenMqUtil.sendMsg(EnumGenHandler.TL_UPLOAD_IMG, "2", uid); // 上传车队长，身份证正面、国徽面
        return Result.OK("开通成功!");
    }

    @Transactional
    public Result<?> createDriverAcccount(HyDriver driver , String source) {
        //检查是否已开通
        String uid = driver.getId();

//        String qualificationImg = driver.getQualificationImg();
//        if(StringUtils.isEmpty(qualificationImg)){
//            return Result.error("从业资格证照片不能为空");
//        }

        HyTlAccount account = tlAccountService.getByUid(uid);
        if (account != null) {
            return Result.error("已开通钱包,不能重复开通");
        }
        //检查是否添加银行卡
        int bankNums = driverBankService.getBankNumsByDriverId(uid);
        if(bankNums == 0){
            return Result.error("未添加银行卡,请先添加银行卡");
        }
        //查找司机车辆
        HyVehicle vehicle = null;
        List<HyVehicle> vehicles = vehicleService.getVehicleByDriverId(uid);
        if (vehicles != null && vehicles.size() > 0) {
            vehicle = vehicles.get(0);
        } else {
            List<HyVehicle> vehicles2 = driverService.getDriverVehicleList(uid);
            if (vehicles2 == null || vehicles2.size() == 0) {
                return Result.error("车牌号不能为空，请添加车辆后再开通钱包");
            }
            vehicle = vehicles2.get(0);
        }

        if (vehicle == null) {
            return Result.error("车牌号不能为空，请添加车辆后再开通钱包");
        }
//        if(StringUtils.isBlank(vehicle.getRoadTransportImg())){
//            return Result.error("车辆道路运输证不能为空");
//        }

        String bizUserId = CodeUtil.createBizUserId(UTypeEnum.DRIVER);
        account = new HyTlAccount();
        account.setAccName(driver.getDriverName());
        account.setUtype(UTypeEnum.DRIVER.uType);
        account.setBizUserId(bizUserId);
        account.setPhone(driver.getTelephone());
        account.setUid(uid);
        account.setSt("1");
        account.setPaySt("0");
        account.setIzOpen("1");
        account.setAmt(BigDecimal.ZERO);
        account.setAvailAmt(BigDecimal.ZERO);
        account.setFrzAmt(BigDecimal.ZERO);
        account.setIzBindBankCard("0");
        account.setIzPhoneChecked("0");
        account.setIzSignContract("0");
        account.setIzOcrIdcard("0");
        account.setIzOcrRegnum("0");
        account.setIzTransportCertificate("0");
        account.setCarId(vehicle.getId());
        tlAccountService.save(account);
        JSONObject ret = TongLianUtil.createPersonMember(bizUserId, driver.getDriverName(), driver.getIdcard(), "2", driver.getTelephone(), vehicle.getVehicleNumber(), source);
        if (!TongLianUtil.isSuccess(ret)) {
            throw new JeecgBootException("开通失败," + TongLianUtil.getMsg(ret));
        }
        JSONObject jd = ret.getJSONObject("data");
        String tlUserId = jd.getString("userId");//云商通会员号
        account.setTlUserId(tlUserId);
        tlAccountService.updateById(account);
        //异步上传 照片
        GenMqUtil.sendMsg(EnumGenHandler.TL_UPLOAD_IMG, "1", uid); // 上传司机，身份证正面、国徽面
        return Result.OK("开通成功!");
    }

    public Result<?> applyDriverBindBankCard(HyDriver driver , HyTlAccount account ,String bankid) {
        HyDriverBank driverBank = driverBankService.getById(bankid);
        if (driverBank == null) {
            return Result.error("银行卡信息不存在");
        }
        if(!StringUtils.equals(driverBank.getDriverId() , driver.getId())){
            return Result.error("银行卡信息错误");
        }
        String bankNum = driverBank.getBankNum();
        if (StringUtils.isBlank(bankNum)) {
            return Result.error("银行卡号不能为空");
        }
        String bankPhone = driverBank.getBankPhone();
        if (StringUtils.isBlank(bankPhone)) {
            return Result.error("银行卡开户预留手机号不能为空");
        }

        String bizUserId = account.getBizUserId();
        JSONObject ret = TongLianUtil.applyBindPersonBankCard(bizUserId, driverBank.getBankName(), driver.getIdcard(), bankPhone, bankNum);
        if (!TongLianUtil.isSuccess(ret)) {
            return Result.error(TongLianUtil.getMsg(ret));
        }
        account.setBankCardNo(bankNum);
        account.setIzBindBankCard("1");
        tlAccountService.updateById(account);
        return Result.OK("绑定成功!");
    }

    public Result<?> applyCarrierBindBankCard(HyCarrier carrier , HyTlAccount account) {
        String bankNum = carrier.getBankNum();
        if (StringUtils.isBlank(bankNum)) {
            return Result.error("银行卡号不能为空");
        }
        String bankPhone = carrier.getTel();
        if (StringUtils.isBlank(bankPhone)) {
            return Result.error("银行卡开户预留手机号不能为空");
        }
        String bizUserId = account.getBizUserId();
        JSONObject ret = TongLianUtil.applyBindPersonBankCard(bizUserId, carrier.getBankName(), carrier.getIdcard(), bankPhone, bankNum);
        if (!TongLianUtil.isSuccess(ret)) {
            return Result.error(TongLianUtil.getMsg(ret));
        }
        account.setBankCardNo(bankNum);
        account.setIzBindBankCard("1");
        tlAccountService.updateById(account);
        return Result.OK("绑定成功!");
    }

    public Result<?> unbindBankCard(HyTlAccount account , String bankCardNo) {
        String bizUserId = account.getBizUserId();
        JSONObject ret = TongLianUtil.unbindBankCard(bizUserId, bankCardNo);
        if (!TongLianUtil.isSuccess(ret)) {
            return Result.error(TongLianUtil.getMsg(ret));
        }
        account.setIzBindBankCard("0");
        account.setPaySt("0");
        tlAccountService.updateById(account);
        return Result.OK("解绑成功!");
    }

    public Result<?> signContract(HyTlAccount account ,String jumpPageType, String source ) {
        String bizUserId = account.getBizUserId();
        JSONObject ret = TongLianUtil.signContract(bizUserId, account.getAccName(), jumpPageType, null, null, source);
        if (!TongLianUtil.isSuccess(ret)) {
            return Result.error(TongLianUtil.getMsg(ret));
        }
        JSONObject data1 = ret.getJSONObject("data");
        return Result.OK(data1.getString("signUrl"));
    }

    public Result<?> uploadDriverImg(HyDriver driver , HyTlAccount account) {
        String idcardImg = driver.getIdcardImg();
        if(StringUtils.isEmpty(idcardImg)){
            return Result.error("司机身份证正面照未上传，请上传后重试");
        }
        String idcardImgBack = driver.getIdcardImgBack();
        if(StringUtils.isEmpty(idcardImgBack)){
            return Result.error("司机身份证国徽面照未上传，请上传后重试");
        }

        File idcardImgZM = new File(uploadpath + "/" + idcardImg);
        if (!idcardImgZM.exists()) {
            return Result.error("司机身份证正面照未上传，请上传后重试");
        }

        File idcardImgGH = new File(uploadpath + "/" + idcardImgBack);
        if (!idcardImgGH.exists()) {
            return Result.error("司机身份证国徽面照未上传，请上传后重试");
        }

        //1：营业执照
        //8：身份证正面（人像面）
        //9：身份证反面（国徽面）
        //10：道路运输经营许可证/道路运输证
        //11：从业资格证
        try {
            String base64 = ImageUtil.compressImgToBase64(idcardImgZM, 800, 600, 200 * 1024);
            JSONObject ret = TongLianUtil.idcardCollect(account.getBizUserId(), "8", base64, null);
            if (!TongLianUtil.isSuccess(ret)) {
                return Result.error(TongLianUtil.getMsg(ret));
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

        try {
            String base64 = ImageUtil.compressImgToBase64(idcardImgGH, 800, 600, 200 * 1024);
            JSONObject ret = TongLianUtil.idcardCollect(account.getBizUserId(), "9", base64, null);
            if (!TongLianUtil.isSuccess(ret)) {
                return Result.error(TongLianUtil.getMsg(ret));
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        account.setIzOcrIdcard("2");
        tlAccountService.updateById(account);
        return Result.OK("证件上传成功，请稍后查看结果");
    }

    public Result<?> uploadDriverImg2(HyDriver driver , HyTlAccount account) {
        String filePath = driver.getQualificationImg();
        if (StringUtils.isBlank(filePath)) {
            filePath = driver.getIdcardImg();
            if (StringUtils.isBlank(filePath)) {
                return Result.error("从业资格证照片未上传，请上传后重试");
            }
        }

        File file = new File(uploadpath + "/" + filePath);
        if (!file.exists()) {
            return Result.error("从业资格证照片未上传，请上传后重试");
        }
        //1：营业执照
        //8：身份证正面（人像面）
        //9：身份证反面（国徽面）
        //10：道路运输经营许可证/道路运输证
        //11：从业资格证
        try {
            String base64 = ImageUtil.compressImgToBase64(file, 800, 600, 200 * 1024);
            JSONObject ret = TongLianUtil.idcardCollect(account.getBizUserId(), "11", base64, null);
            if (!TongLianUtil.isSuccess(ret)) {
                return Result.error(TongLianUtil.getMsg(ret));
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        account.setIzOcrRegnum("1");//todo   暂时直接=1 ， 司机从业资格证不校验
        tlAccountService.updateById(account);
        return Result.OK("证件上传成功，请稍后查看结果");
    }

    public Result<?> uploadDriverTransportCertificateImg(HyTlAccount account) {
        if(StringUtils.isBlank(account.getCarId())){
            return Result.error("钱包车辆信息不存在");
        }
        HyVehicle vehicle = vehicleService.getById(account.getCarId());
        if(vehicle == null){
            return Result.error("司机车辆信息不存在");
        }
        String filePath = vehicle.getRoadTransportImg();
        if(StringUtils.isBlank(filePath)){
            filePath = vehicle.getDrivingLicenseImg();
            if(StringUtils.isBlank(filePath)){
                return Result.error("车辆道路运输证照片未上传，请上传后重试");
            }
        }

        File file = new File(uploadpath + "/" + filePath);
        if (!file.exists()) {
            return Result.error("车辆道路运输证照片未上传，请上传后重试");
        }
        //1：营业执照
        //8：身份证正面（人像面）
        //9：身份证反面（国徽面）
        //10：道路运输经营许可证/道路运输证
        //11：从业资格证
        try {
            String base64 = ImageUtil.compressImgToBase64(file, 800, 600, 200 * 1024);
            JSONObject ret = TongLianUtil.idcardCollect(account.getBizUserId(), "10", base64, null);
            if (!TongLianUtil.isSuccess(ret)) {
                return Result.error(TongLianUtil.getMsg(ret));
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        account.setIzTransportCertificate("1");//todo   暂时直接=1 ， 司机从业资格证不校验
        tlAccountService.updateById(account);
        return Result.OK("证件上传成功，请稍后查看结果");
    }

    public Result<?> uploadCarrierImg(HyTlAccount account, HyCarrier carrier) {
        String idcardImg = carrier.getIdcardImg();
        if(StringUtils.isEmpty(idcardImg)){
            return Result.error("身份证正面照未上传，请上传后重试");
        }
        String idcardImgBack = carrier.getIdcardImgBack();
        if(StringUtils.isEmpty(idcardImgBack)){
            return Result.error("身份证国徽面照未上传，请上传后重试");
        }
        File idcardImgZM = new File(uploadpath + "/" + idcardImg);
        if (!idcardImgZM.exists()) {
            return Result.error("身份证正面照未上传，请上传后重试");
        }

        File idcardImgGH = new File(uploadpath + "/" + idcardImgBack);
        if (!idcardImgGH.exists()) {
            return Result.error("身份证国徽面照未上传，请上传后重试");
        }
        //1：营业执照
        //8：身份证正面（人像面）
        //9：身份证反面（国徽面）
        //10：道路运输经营许可证/道路运输证
        //11：从业资格证
        try {
            String base64 = ImageUtil.compressImgToBase64(idcardImgZM, 800, 600, 200 * 1024);
            JSONObject ret = TongLianUtil.idcardCollect(account.getBizUserId(), "8", base64, null);
            if (!TongLianUtil.isSuccess(ret)) {
                return Result.error(TongLianUtil.getMsg(ret));
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

        try {
            String base64 = ImageUtil.compressImgToBase64(idcardImgGH, 800, 600, 200 * 1024);
            JSONObject ret = TongLianUtil.idcardCollect(account.getBizUserId(), "9", base64, null);
            if (!TongLianUtil.isSuccess(ret)) {
                return Result.error(TongLianUtil.getMsg(ret));
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        account.setIzOcrIdcard("2");
        tlAccountService.updateById(account);
        return Result.OK("证件上传成功，请稍后查看结果");
    }
    /**
     *
     * @param account
     * @param phone
     * @param verificationCodeType  验证码类型 9-绑定手机;6-解绑手机
     * @return
     */
    public Result<?> sendVerificationCode(HyTlAccount account, String phone, String verificationCodeType) {
        JSONObject ret = TongLianUtil.sendVerificationCode(account.getBizUserId(), phone, verificationCodeType); //9绑定
        if (!TongLianUtil.isSuccess(ret)) {
            return Result.error(TongLianUtil.getMsg(ret));
        }
        return Result.OK("发送成功");
    }

    public Result<?> bindPhone(HyTlAccount account, String phone, String verificationCode) {
        JSONObject ret = TongLianUtil.bindPhone(account.getBizUserId(), phone, verificationCode);
        if (!TongLianUtil.isSuccess(ret)) {
            return Result.error(TongLianUtil.getMsg(ret));
        }
        if(!StringUtils.equals(phone,account.getPhone())){
            account.setPhone(phone);
        }
        account.setIzPhoneChecked("1");
        tlAccountService.updateById(account);
        return Result.OK("绑定成功");
    }

    public Result<?> unbindPhone(HyTlAccount account, String phone, String verificationCode) {
        JSONObject ret = TongLianUtil.unbindPhone(account.getBizUserId(), phone, verificationCode);
        if (!TongLianUtil.isSuccess(ret)) {
            return Result.error(TongLianUtil.getMsg(ret));
        }
        account.setIzPhoneChecked("0");
        account.setPaySt("0");
        tlAccountService.updateById(account);
        return Result.OK("解绑成功");
    }


}
